// =================================================================================================
//
//	CopyEngine Framework
//	Copyright 2012 Eran. All Rights Reserved.
//
//	This program is free software. You can redistribute and/or modify it
//	in accordance with the terms of the accompanying license agreement.
//
// =================================================================================================

/**
 * Created by eran on 14-12-21.
 */
package gui.manger
{
    import data.DataVoManger;
    import data.MapVo;

    import flash.events.Event;
    import flash.filesystem.File;
    import flash.filesystem.FileMode;
    import flash.filesystem.FileStream;

    import gui.utils.blockEditor.BlockEditorDialog;
    import gui.utils.MessageBox;

    public class GUIManger
    {
        private var mDTO:GUIMangerDTO;

        private var mCurrentFile:File;

        public function GUIManger()
        {
        }

        //=================================//
        //=== Initialize & Dispose ========//
        //=================================//
        public function initialize(_dto:GUIMangerDTO):void
        {
            mDTO = _dto;
        }

        //===================//
        //==  点击MapEditor ==//
        //===================//

        public function onClickTileInMap(_tileIndexX:int, _tileIndexY:int):void
        {
            BlockEditorDialog.instance.show(_tileIndexX, _tileIndexY, onTileVoChangeCallback);
        }

        private function onTileVoChangeCallback():void
        {
            mDTO.mapEditor.refreshAllBlcokVo();
        }

        //===================//
        //==  更改地图大小   ==//
        //===================//

        public function onClickSaveMapSettingBtn(_xTileNum:int, _yTileNum:int):void
        {
            if (_xTileNum > 0 && _yTileNum > 0)
            {
                var mapVo:MapVo = DataVoManger.instance.mapVo;
                mapVo.xTileNum = _xTileNum;
                mapVo.yTileNum = _yTileNum;
                mDTO.mapEditor.refreshMapScene();
            }
            else
            {
                MessageBox.instance.showMsg("新地图尺寸不合法, x: " + _xTileNum + ", y: " + _yTileNum);
            }

        }


        //=====================//
        //==  文件保存/读取  ====//
        //=====================//

        /**
         * 打开文件
         */
        public function onClickOpenBtn():void
        {
            mCurrentFile = new File();
            mCurrentFile.browseForOpen("选择Layout文件");
            mCurrentFile.addEventListener(Event.SELECT, onSelectOpenFile);
        }

        private function onSelectOpenFile(e:Event):void
        {
            var isOpenFileError:Boolean = true;
            try
            {
                var fileStream:FileStream = new FileStream();
                fileStream.open(mCurrentFile, FileMode.READ);
                var jsonString:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
                DataVoManger.instance.fromJSON(JSON.parse(jsonString));
                fileStream.close();
                isOpenFileError = false;
            } catch (e:Error)
            {
                mCurrentFile = null;
                MessageBox.instance.showMsg("无法打开文件,格式不对或已损坏");
            }

            if (!isOpenFileError)
            {
                MessageBox.instance.showMsg("打开成功!");

                //刷新文件操作区域
                mDTO.fileOperate.refresh(mCurrentFile);

                //刷新地图编辑区域
                mDTO.mapSetting.refresh();

                //刷新地图区域
                mDTO.mapEditor.refreshAll();

            }
        }

        /**
         * 保存文件
         */
        public function onClickSaveBtn():void
        {
            if (mCurrentFile == null)
            {
                mCurrentFile = new File();
                mCurrentFile.browseForSave("选择保存的位置");
                mCurrentFile.addEventListener(Event.SELECT, onSelectSaveFile);
            }
            else
            {
                doSaveFile();
            }
        }

        private function onSelectSaveFile(e:Event):void
        {
            doSaveFile();
        }

        private function doSaveFile():void
        {
            var jsonString:String = DataVoManger.instance.toJSONString();
            if (jsonString == null)
            {
                MessageBox.instance.showMsg("没有东西,存什么啊?");
            }
            else if (jsonString == "ERROR")
            {
                MessageBox.instance.showMsg("文件 ToJson异常,请联系Eran");
            }
            else
            {
                var isSaveFileError:Boolean = true;
                try
                {
                    mCurrentFile.exists && mCurrentFile.deleteFile();
                    var fileStream:FileStream = new FileStream();
                    fileStream.open(mCurrentFile, FileMode.WRITE);
                    fileStream.writeUTFBytes(jsonString);
                    fileStream && fileStream.close();
                    fileStream = null;
                    isSaveFileError = false;
                } catch (e:Error)
                {
                    MessageBox.instance.showMsg("错误!  无法保存文件");
                }

                if (!isSaveFileError)
                {
                    MessageBox.instance.showMsg("保存成功!");
                    mDTO.fileOperate.refresh(mCurrentFile);
                }
            }
        }


    }
}
